<template>
  <th-button :size="size" :type="type" :disabled="disabled" @click="printCode" @close="closeHandle">
    <slot></slot>
  </th-button>
  <th-dialog title="请选择打印设备" v-model:visible="deviceVisible">
    <template v-slot:content>
      <view class="body">
        <view class="device-list">
          <view
            class="device"
            v-for="d in setting.bluetoothDevices"
            :key="d.deviceId"
            :class="[d.deviceId === setting.currentDevice ? 'current' : '']"
          >
            {{ d.name }}
            <button
              v-if="d.deviceId === setting.currentDevice"
              type="success"
              size="mini"
              style="margin: 0"
            >
              已连接
            </button>
            <button
              v-else
              type="primary"
              size="mini"
              style="margin: 0"
              :loading="connectingId === d.deviceId"
              @click="createBLEConnection(d)"
            >
              连接
            </button>
          </view>
        </view>
        <view class="tip">正在搜索蓝牙设备...</view>
      </view>
    </template>
  </th-dialog>
</template>

<script lang="ts" setup name="PrintButton">
import { useSetting } from '@/stores/setting';
import { connectBlue } from '@/utils/print';
import thButton from './th-button.vue';
import thDialog from './th-dialog.vue';

defineProps({
  type: {
    type: String,
  },
  border: {
    type: [Boolean, String],
    default: false,
  },
  disabled: {
    type: [Boolean, String],
    default: false,
  },
  size: {
    type: String,
  },
});

const emit = defineEmits(['print']);

// 打印
const deviceVisible = ref(false);
const setting = useSetting();
const connectingId = ref('');
const sleep = ref(false);
const createBLEConnection = async (device: any) => {
  connectingId.value = device.deviceId;
  const ret = await connectBlue(device);
  connectingId.value = '';
  if (ret) {
    uni.hideLoading();
    setting.currentDevice = device.deviceId;
    deviceVisible.value = false;
    setting.setConnect(true);
  } else {
    uni.showToast({
      title: '连接失败',
      icon: 'none',
    });
  }
};

const printCode = () => {
  if (sleep.value) return;
  sleep.value = true;
  if (setting.connected) {
    emit('print');
  } else {
    uni.openBluetoothAdapter({
      success() {
        deviceVisible.value = true;
        if (setting.bluetoothDevices.length) return;
        getDeviceList();
      },
      fail() {
        uni.showToast({
          title: '请检查蓝牙是否打开',
          icon: 'none',
        });
      },
    });
  }
  setTimeout(() => {
    sleep.value = false;
    uni.hideToast();
  }, 1500);
};

const getDeviceList = () => {
  uni.openBluetoothAdapter({
    success() {
      uni.startBluetoothDevicesDiscovery({
        allowDuplicatesKey: true,
        success: () => {
          console.log('开始搜索设备');
          setting.setBluetoothDevices();
        },
      });
    },
    fail(err) {
      console.log('err', err);
    },
  });
};

const closeHandle = () => {
  uni.closeBluetoothAdapter();
  uni.stopBeaconDiscovery();
  uni.offBluetoothDeviceFound();
};

// onMounted(() => {
//   // 获取蓝牙设备
//   uni.onBLEConnectionStateChange((res) => {
//     if (res.connected) {
//       setting.setConnect(true);
//       currentDevice.value = res.deviceId;
//     } else {
//       uni.closeBLEConnection({
//         deviceId: res.deviceId,
//       });
//       setting.setConnect(false);
//       currentDevice.value = '';
//       // printModule.closePort();
//     }
//   });
// });
</script>

<style lang="scss" scoped>
.body {
  // height:;
  .tip {
    text-align: center;
    padding: 20rpx;
    font-size: 26rpx;
  }
}
.device-list {
  max-height: 70vh;
  .device {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15rpx;
    border-bottom: 1rpx solid #f2f2f2;
    &.current {
      color: blue;
    }
  }
}
</style>
